import mongoose from "mongoose"
import connectToDatabase from "./db"
import Post, { IPost } from "../models/Post"
import User from "../models/User"

class PostService {
  // 连接数据库（可选）
  private static async connect() {

    if (mongoose.connection.readyState === 0) {
      await connectToDatabase()
    }
  }

  // 创建新文章
  static async createPost(
    title: string,
    content: Array<any>,
    author: string,
    auth: string = "all"
  ): Promise<IPost> {
    await this.connect()
    // console.log(auth)
    return Post.create({ title, content, author, auth })
  }

  // 获取所有文章
  static async getAllPosts(): Promise<IPost[]> {
    await this.connect()
    return Post.find()
      .where("auth")
      .equals("all") // 只获取 author === 'all' 的数据
      .select("title cover createdAt") // 选取 title、cover 和 createdAt 字段
      .sort({ createdAt: -1 }) // 按 createdAt 降序排序（最新的在前）
      .exec()
  }

  // 获取单篇文章
  static async getPostById(postId: string): Promise<IPost | null> {
    await this.connect()
    return Post.findById(postId)
  }

  static async getPostsByAuthor(author: string): Promise<IPost[]> {
    await this.connect();
    return Post.find({ author }); // 查找所有匹配的帖子
  }

  // 分页获取文章
  static async getPagePostById(
    postId: string,
    page: number,
    pageSize: number
  ): Promise<IPost | null> {
    await this.connect()

    // 计算 skip 和 limit
    const skip = (page - 1) * pageSize
    const limit = pageSize

    // 使用 $slice 操作符来分页获取 content
    const post = await Post.findById(postId, {
      content: { $slice: [skip, limit] },
      cover: 1,
      title: 1,
      author: 1,
      auth: 1,
      createdAt: 1,
      updatedAt: 1,
    })

    return post
  }


  static async getUserCollect(userId: string): Promise<IPost | null> {
    await this.connect()
    // 查找用户
    const user = await User.findById(userId);
    if (!user) {
      throw null;
    }

    // 获取 bookshelf 数组中的 bookIds
    const bookshelfIds = user.bookshelf;  // 假设 bookshelf 是 [book1Id, book2Id, book3Id]

    // 查找所有书籍信息
    const books = await Post.find({
      _id: { $in: bookshelfIds }  // 使用 $in 操作符查找所有书籍
    });

    // 返回书籍详细信息
    return books as any;
  }

  // 更新文章
  static async updatePost(
    postId: string,
    updateData: Partial<IPost>
  ): Promise<IPost | null> {
    await this.connect()
    return Post.findByIdAndUpdate(postId, updateData, { new: true })
  }

  // 删除文章
  static async deletePost(postId: string): Promise<IPost | null> {
    await this.connect()
    return Post.findByIdAndDelete(postId)
  }
}

export default PostService
